import 'package:flutter/material.dart';
import 'package:lib_core/lib_core.dart';

abstract class PagerSheet extends StatelessWidget {
  PagerSheet({Key? key}) : super(key: key);

  final PageController pageCtrl = PageController();

  abstract double? height;
  abstract Widget initialWidget;
  bool needAnim = true;

  late final RxList<Widget> children = [initialWidget].obs;

  int index = 0;

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: const BorderRadius.only(
        topLeft: Radius.circular(21),
        topRight: Radius.circular(21),
      ),
      child: Container(
        height: height ?? Get.height * 0.85,
        color: Colors.white,
        child: Obx(() {
          return PageView(
            controller: pageCtrl,
            physics:
            children.length == 1 ? const NeverScrollableScrollPhysics() : const NeverScrollableScrollPhysics(),
            children: children,
          );
        }),
      ),
    );
  }

  void onNext(Widget widget) {
    children.add(widget);
    // animateTo会触发子组件的重建，jumpTo不会
    if (needAnim) {
      pageCtrl.animateToPage(++index, duration: 300.milliseconds, curve: Curves.linear);
    } else {
      pageCtrl.jumpToPage(++index);
    }
  }

  void onPrevious() {
    if (index == 0) {
      BoostNavigator.instance.pop();
    } else {
      children.removeLast();
      if (needAnim) {
        pageCtrl.animateToPage(--index, duration: 300.milliseconds, curve: Curves.linear);
      } else {
        pageCtrl.jumpToPage(--index);
      }
    }
  }

  void dismiss() {
    BoostNavigator.instance.pop();
  }
}
